using Game.NetWork;
using Game.NetWork.Packages;
using Game.Server;
using Engine;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace Game.Plugin.MyShopPlugin
{
    public class MyShopMarketCmd : AbstractProcessCmd
    {
        public override string Cmd => "s";
        public override string Introduce => "/s    -黑市交易相关的命令";
        public override int AuthLevel => 0;
        public override DisplayType Display => DisplayType.All;

        private readonly ItemNameHelper _itemNameHelper = new ItemNameHelper();

        public void SendMarketHelpMessage()
        {
            string message = "\n/s hs        - 查看黑市物品列表\n/s sellmy <数量> <价格> <物品> - 上架物品到黑市\n/s buyp <序号> - 购买黑市物品（使用/s hs查看序号）\n<<<======【黑市交易】MyShop黑市系统======>>>";
            SendMessage("黑市系统", message);
        }

        public override void ProcessCmd()
        {
            if (GameManager.Project == null)
            {
                SendMessage("<c=red>主系统</c>", "你需要先开始游戏");
                return;
            }

            if (m_isTerminal)
            {
                SendMessage("<c=red>主系统</c>", "控制台无法使用");
                return;
            }

            string playerGuid = m_client.GUID.ToString();
            ComponentPlayer componentPlayer = m_client.PlayerData.ComponentPlayer;

            if (m_messageDatas.Length < 2)
            {
                SendMarketHelpMessage();
                return;
            }

            // 检查操作冷却时间
            if (!MyShopData.CheckCooldown(playerGuid, 1))
            {
                SendMessage("<c=red>黑市</c>", "请稍后再操作");
                return;
            }

            switch (m_messageDatas[1])
            {
                case "hs":
                    ShowBlackMarketItems();
                    break;

                case "sellmy":
                    if (m_messageDatas.Length == 5)
                    {
                        SellItemToBlackMarket(componentPlayer, m_messageDatas);
                    }
                    else
                    {
                        SendMessage("<c=red>黑市</c>", "使用方法: /s sellmy <数量> <价格> <物品>");
                    }
                    break;

                case "buyp":
                    if (m_messageDatas.Length == 3)
                    {
                        if (int.TryParse(m_messageDatas[2], out int itemId))
                        {
                            BuyFromBlackMarket(componentPlayer, itemId);
                        }
                        else
                        {
                            SendMessage("<c=red>黑市</c>", "序号必须是数字");
                        }
                    }
                    else
                    {
                        SendMessage("<c=red>黑市</c>", "使用方法: /s buyp <序号>");
                    }
                    break;

                default:
                    SendMarketHelpMessage();
                    break;
            }
        }

        private void ShowBlackMarketItems()
        {
            var items = MyShopData.GetBlackMarketItems();
            if (items.Count == 0)
            {
                SendMessage("<c=red>黑市</c>", "当前黑市没有任何物品");
                return;
            }

            string message = "\n========== 黑市物品列表 ==========\n";
            foreach (var item in items)
            {
                string itemName = _itemNameHelper.GetItemName(item.ContentItemId);
                message += $"[{item.ItemId}] {itemName} * {item.Count} - {item.Price}金币 (卖家: {item.SellerName})\n";
            }
            message += "使用 /s buyp <序号> 购买物品\n";
            message += "=================================";
            SendMessage("<c=red>黑市</c>", message);
        }

        private void SellItemToBlackMarket(ComponentPlayer componentPlayer, string[] messageDatas)
        {
            string playerGuid = componentPlayer.PlayerData.Client.GUID.ToString();
            string playerName = componentPlayer.PlayerData.Name;

            // 解析参数
            if (!int.TryParse(messageDatas[2], out int count) || count <= 0)
            {
                SendMessage("<c=red>黑市</c>", "数量必须是正整数");
                return;
            }

            if (!int.TryParse(messageDatas[3], out int price) || price <= 0)
            {
                SendMessage("<c=red>黑市</c>", "价格必须是正整数");
                return;
            }

            if (price > 3000)
            {
                SendMessage("<c=red>黑市</c>", "价格不能超过3000金币");
                return;
            }

            // 解析物品ID
            string itemText = messageDatas[4];
            string pattern = @"<b>(.*?)</b>";
            Match match = Regex.Match(itemText, pattern);
            if (!match.Success)
            {
                SendMessage("<c=red>黑市</c>", "请拖拽物品到聊天框来指定物品");
                return;
            }

            if (!int.TryParse(match.Groups[1].Value, out int itemId))
            {
                SendMessage("<c=red>黑市</c>", "物品ID格式错误");
                return;
            }

            // 检查玩家是否有足够的物品
            ComponentInventory inventory = componentPlayer.Entity.FindComponent<ComponentInventory>();
            bool hasItem = false;
            int slotIndex = -1;

            for (int i = 0; i < inventory.SlotsCount; i++)
            {
                int slotValue = inventory.GetSlotValue(i);
                int slotCount = inventory.GetSlotCount(i);
                if (slotValue == itemId && slotCount >= count)
                {
                    hasItem = true;
                    slotIndex = i;
                    break;
                }
            }

            if (!hasItem)
            {
                SendMessage("<c=red>黑市</c>", "你没有足够的物品上架");
                return;
            }

            // 检查玩家金钱限制
            MyShopListData playerData = MyShopData.GetDataByGuid(playerGuid);
            if (playerData != null && playerData.playerMoney >= 10000)
            {
                SendMessage("<c=red>黑市</c>", "你的余额已很多，不能再上架物品");
                return;
            }

            // 添加黑市物品
            if (MyShopData.AddBlackMarketItem(playerGuid, playerName, itemId, price, count))
            {
                // 从玩家背包移除物品
                inventory.RemoveSlotItems(slotIndex, count);
                string itemName = _itemNameHelper.GetItemName(itemId);

                // 获取新上架物品的序号
                var newItem = MyShopData.BlackMarketItems[MyShopData.BlackMarketItems.Count - 1];

                SendMessage("<c=green>黑市</c>", $"成功上架 {count} 个 {itemName}，价格: {price} 金币，序号: {newItem.ItemId}");

                // 广播消息
                GameManager.Project.FindSubsystem<SubsystemGameWidgets>().AddMessage(
                    $"玩家 <c=blue>{playerName}</c> 上架了 {count} 个 <b>{itemId}</b> 到黑市，价格: {price} 金币",
                    null, 0, null);
            }
            else
            {
                SendMessage("<c=red>黑市</c>", "上架失败：你已达到上架物品数量上限（最多3个）");
            }
        }

        private void BuyFromBlackMarket(ComponentPlayer componentPlayer, int itemId)
        {
            string buyerGuid = componentPlayer.PlayerData.Client.GUID.ToString();
            string buyerName = componentPlayer.PlayerData.Name;

            // 购买黑市物品
            if (MyShopData.BuyBlackMarketItem(buyerGuid, itemId, out BlackMarketItem item))
            {
                // 检查买家金钱
                MyShopListData buyerData = MyShopData.GetDataByGuid(buyerGuid);
                if (buyerData == null || buyerData.playerMoney < item.Price)
                {
                    SendMessage("<c=red>黑市</c>", "你的金币不足");
                    // 把物品重新加回黑市
                    MyShopData.BlackMarketItems.Add(item);
                    MyShopData.SaveBlackMarketData();
                    return;
                }

                // 检查背包空间
                ComponentInventory inventory = componentPlayer.Entity.FindComponent<ComponentInventory>();
                bool hasSpace = false;
                int slotIndex = -1;

                for (int i = 0; i < inventory.SlotsCount; i++)
                {
                    int slotValue = inventory.GetSlotValue(i);
                    int slotCount = inventory.GetSlotCount(i);
                    int slotCapacity = inventory.GetSlotCapacity(i, item.ContentItemId);
                    if ((slotCount == 0 || slotValue == item.ContentItemId) && slotCount + item.Count <= slotCapacity)
                    {
                        hasSpace = true;
                        slotIndex = i;
                        break;
                    }
                }

                if (!hasSpace)
                {
                    SendMessage("<c=red>黑市</c>", "你的背包空间不足");
                    // 把物品重新加回黑市
                    MyShopData.BlackMarketItems.Add(item);
                    MyShopData.SaveBlackMarketData();
                    return;
                }

                // 执行交易
                // 扣除买家金钱
                MyShopListData newBuyerData = new MyShopListData
                {
                    playerMoney = buyerData.playerMoney - item.Price,
                    playerGuid = buyerData.playerGuid,
                    playerName = buyerData.playerName,
                    lastSignInTime = buyerData.lastSignInTime
                };
                MyShopData.SetMyShopListDataByGuid(buyerGuid, newBuyerData);

                // 给卖家加钱
                MyShopListData sellerData = MyShopData.GetDataByGuid(item.SellerGuid);
                if (sellerData != null) // 增加判断
                {
                    MyShopListData newSellerData = new MyShopListData
                    {
                        playerMoney = sellerData.playerMoney + item.Price,
                        playerGuid = sellerData.playerGuid,
                        playerName = sellerData.playerName,
                        lastSignInTime = sellerData.lastSignInTime
                    };
                    MyShopData.SetMyShopListDataByGuid(item.SellerGuid, newSellerData);
                }
                else
                {
                    Log.Error($"卖家 {item.SellerName}（GUID: {item.SellerGuid}）数据不存在，无法发放交易金额");
                }

                // 给买家物品
                inventory.AddSlotItems(slotIndex, item.ContentItemId, item.Count);

                string itemName = _itemNameHelper.GetItemName(item.ContentItemId);
                SendMessage("<c=green>黑市</c>", $"成功购买 {item.Count} 个 {itemName}，花费: {item.Price} 金币");

                // 通知卖家
                if (sellerData != null)
                {
                    foreach (var player in GameManager.Project.FindSubsystem<SubsystemPlayers>().PlayersData)
                    {
                        if (player.Client.GUID.ToString() == item.SellerGuid)
                        {
                            SendMsgPack(player.ComponentPlayer, $"你上架的 {item.Count} 个 {itemName} 已被玩家 {buyerName} 购买，获得: {item.Price} 金币");
                            break;
                        }
                    }
                }

                // 广播消息
                GameManager.Project.FindSubsystem<SubsystemGameWidgets>().AddMessage(
                    $"玩家 <c=blue>{buyerName}</c> 购买了 {item.SellerName} 上架的 {item.Count} 个 <b>{item.ContentItemId}</b>",
                    null, 0, null);
            }
            else
            {
                SendMessage("<c=red>黑市</c>", "购买失败：物品不存在或不能购买自己的物品");
            }
        }

        private void SendMsgPack(ComponentPlayer componentPlayer, string text)
        {
            MessagePackage messagePackage = new MessagePackage(null, text, 0, null);
            messagePackage.To = componentPlayer.PlayerData.Client;
            CommonLib.Net.QueuePackage(messagePackage);
        }
    }

    // 物品名称帮助类
    public class ItemNameHelper
    {
        public string GetItemName(int itemId)
        {
            // 这里可以添加物品ID到名称的映射
            // 为了简洁，这里只返回ID，您可以根据需要扩展这个映射
            return $"物品[{itemId}]";
        }
    }
}